package com.cloudbroker.bcs.csvc.lightinvesting.facade.service.aspect;

import com.cloudbroker.bcs.common.annotation.DecodePwd;
import com.cloudbroker.bcs.common.util.PrintUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.bouncycastle.util.encoders.Base64;;
import util.RSAEncrypt;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * Created by tianrui on 2016/9/27.
 */
public class DecodeTradePwdAspect {

    private static final String CLASS_NAME = AuthCheckAspect.class.getName();

    private static final Logger LOGGER = LoggerFactory.getLogger(CLASS_NAME);

    private static final String NEED_DECODE_PWD = "2";

    public DecodeTradePwdAspect() { PrintUtil.printComponentLoaded(LOGGER, CLASS_NAME); }

    public Object checkDecodePwd(ProceedingJoinPoint pjp) throws Throwable {
        // 在Spring的环境里，signature就是MethodSignature
        MethodSignature methodSignature = (MethodSignature) pjp.getSignature();
        // 获取Method
        Method method = methodSignature.getMethod();
        //判断是否需要解密
        if (method.isAnnotationPresent(DecodePwd.class)) {
            //反射拿到需解密password
            Object[] args = pjp.getArgs();
            for (Object obj : args) {
                try {
                    String password_type = (String) obj.getClass().getMethod("getPassword_type").invoke(obj);
                    if (password_type.equals(NEED_DECODE_PWD)) {
                        String password = (String) obj.getClass().getMethod("getPassword").invoke(obj);
                        byte[] res= RSAEncrypt.decrypt(RSAEncrypt.loadPrivateKeyByStr(), Base64.decode(password));
                        String newPassword = new String(res);
                        obj.getClass().getMethod("setPassword", String.class).invoke(obj, newPassword);
                    }
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                }
            }
        }
        return pjp.proceed();
    }
}

